package com.lookme.lmtool.view;

import com.lookme.lmtool.controller.CaptchaCrackerController;
import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.util.Callback;
import netscape.javascript.JSObject;

import java.net.URL;

public class CodeWebView {
    WebEngine webEngine;
    boolean inited=false;
    String script;
    Callback<String,Void> callback;
    public CodeWebView(WebView webView, String script,Callback<String,Void> callback){
        this.webEngine=webView.getEngine();
        this.script=script;
        this.callback=callback;

        URL url = getClass().getResource("/codemirror/java.html");
        webEngine.setJavaScriptEnabled(true);
        WebEngine finalWebEngine = webEngine;
        webEngine.getLoadWorker().stateProperty().addListener(
                (ObservableValue<? extends Worker.State> ov, Worker.State oldState, Worker.State newState) -> {
                    if (newState == Worker.State.SUCCEEDED) {
                        JSObject window = (JSObject) finalWebEngine.executeScript("window");
                        window.setMember("apps", CodeWebView.this);
                        window.setMember("sout", System.out);
                        initScriptConfig();
                    }
                }
        );
        webEngine.load(url.toExternalForm());
    }


    private void initScriptConfig() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(webEngine.getDocument()==null){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    }
                }
                inited=true;
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        webEngine.executeScript("editor.setValue(window.apps.getScript())");
                    }
                });
            }
        }).start();
    }

    public void change(String script){
        this.script=script;
        if(callback!=null){
            callback.call(script);
        }
    }


    public void setScript(String script){
        this.script=script;
        try {
            webEngine.executeScript("editor.setValue(window.apps.getScript())");
        }catch(Exception e){

        }
    }
    public void setInited(){
        this.inited=true;
        webEngine.executeScript("editor.setValue(window.apps.getScript())");
    }

    public String getScript(){
        return script;
    }
}
